package com.mixide.ui.part.register;

import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.TableItem;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class RegisterCellModifier implements ICellModifier {
	
	private final TableViewer tableViewer;
	
	public boolean canModify(Object element, String property) {
		if ("toChar".equals(property) || "toInt".equals(property) || "no".equals(property)) {
			return false;
		}
		return true;
	}

	public Object getValue(Object element, String property) {
		if (!(element instanceof RegisterRow)) {
			return null;
		}
		RegisterRow row = (RegisterRow) element;
		if ("sign".equals(property)) {
			return "+".equals(row.getSign()) ? 0 : 1;
		}
		if ("byte1".equals(property)) {
			return row.getByte1();
		}
		if ("byte2".equals(property)) {
			return row.getByte2();
		}
		if ("byte3".equals(property)) {
			return row.getByte3();
		}
		if ("byte4".equals(property)) {
			return row.getByte4();
		}
		if ("byte5".equals(property)) {
			return row.getByte5();
		}
		if ("toChar".equals(property)) {
			return row.getToChar();
		}
		if ("toInt".equals(property)) {
			return row.getToInt();
		}
		return "";
	}

	public void modify(Object element, String property, Object value) {
		if (!(element instanceof TableItem)) {
			return;
		}
		element = ((TableItem) element).getData();
		if (!(element instanceof RegisterRow)) {
			return;
		}
		RegisterRow row = (RegisterRow) element;
		if ("sign".equals(property)) {
			row.setSign("0".equals(value.toString()) ? "+" : "-");
		} else if ("byte1".equals(property)) {
			row.setByte(1, value.toString());
		} else if ("byte2".equals(property)) {
			row.setByte(2, value.toString());
		} else if ("byte3".equals(property)) {
			row.setByte(3, value.toString());
		} else if ("byte4".equals(property)) {
			row.setByte(4, value.toString());
		} else if ("byte5".equals(property)) {
			row.setByte(5, value.toString());
		} else if ("toChar".equals(property)) {
			row.setToChar(value.toString());
		} else if ("toInt".equals(property)) {
			row.setToInt(value.toString());
		}
		this.tableViewer.update(row, null);
	}
}
